package per.wsj.paging

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rv.layoutManager = LinearLayoutManager(this)
        val adapter = StudentAdapter()
        rv.adapter = adapter

        val config = PagedList.Config.Builder()
            .setInitialLoadSizeHint(20)
            .setPageSize(20)
//            .setMaxSize(20 + 2 * 3)
            .setPrefetchDistance(5)//设置距离最后还有多少个item时，即自动加载下一页的数据；
            .setEnablePlaceholders(true)//表示是否设置null占位符；
            .build()

        val repository = CustomRepository()
        val factory = CustomPageDataSourceFactory(repository)
        val liveData: LiveData<PagedList<StudentModel>> =
            LivePagedListBuilder(factory, config).build()

        liveData.observe(this, Observer{
            adapter.submitList(it)
        })
    }
}
